// 导入ApiService
import ApiService from './ApiService.js';

class CustomerStore {
  constructor() {
    this.customers = [];
    this.listeners = [];
    this.isLoading = false;
    this.error = null;
    
    // 从localStorage加载数据作为初始数据
    this.loadFromStorage();
  }
  
  // 从API加载数据
  async loadCustomers() {
    this.isLoading = true;
    this.error = null;
    try {
      const response = await ApiService.getCustomers();
      if (response.success) {
        this.customers = response.data;
        this.saveToStorage(); // 缓存到本地
        this.notifyListeners();
        return true;
      } else {
        throw new Error('Failed to load customers');
      }
    } catch (error) {
      console.error('Failed to load customers from API:', error);
      this.error = error.message || '加载客户数据失败';
      // 如果API失败，确保我们有数据可用
      if (this.customers.length === 0) {
        this.loadFromStorage();
      }
      return false;
    } finally {
      this.isLoading = false;
    }
  }
  
  // 添加监听器
  addListener(listener) {
    this.listeners.push(listener);
  }
  
  // 移除监听器
  removeListener(listener) {
    this.listeners = this.listeners.filter(l => l !== listener);
  }
  
  // 通知所有监听器数据已更新
  notifyListeners() {
    this.listeners.forEach(listener => listener());
  }
  
  // 保存数据到localStorage
  saveToStorage() {
    localStorage.setItem('customersData', JSON.stringify(this.customers));
  }
  
  // 从localStorage加载数据
  loadFromStorage() {
    const savedData = localStorage.getItem('customersData');
    if (savedData) {
      try {
        this.customers = JSON.parse(savedData);
      } catch (e) {
        console.error('Failed to load customers from localStorage:', e);
      }
    } else {
      // 如果没有缓存数据，使用默认数据
      this.customers = [
        {
          id: 1,
          name: '张三',
          phone: '13800138001',
          email: 'zhangsan@example.com',
          address: '北京市朝阳区建国路88号',
          registerDate: '2023-05-15T10:30:00',
          lastLogin: '2023-11-15T14:20:00',
          status: 'active',
          orderCount: 5,
          totalSpent: 15899,
          avatar: 'https://picsum.photos/seed/customer1/200/200'
        },
        {
          id: 2,
          name: '李四',
          phone: '13900139002',
          email: 'lisi@example.com',
          address: '上海市浦东新区张江高科技园区',
          registerDate: '2023-06-20T09:15:00',
          lastLogin: '2023-11-10T16:45:00',
          status: 'active',
          orderCount: 3,
          totalSpent: 8999,
          avatar: 'https://picsum.photos/seed/customer2/200/200'
        },
        {
          id: 3,
          name: '王五',
          phone: '13700137003',
          email: 'wangwu@example.com',
          address: '广州市天河区天河路385号',
          registerDate: '2023-07-05T11:20:00',
          lastLogin: '2023-10-25T08:30:00',
          status: 'active',
          orderCount: 2,
          totalSpent: 6599,
          avatar: 'https://picsum.photos/seed/customer3/200/200'
        },
        {
          id: 4,
          name: '赵六',
          phone: '13600136004',
          email: 'zhaoliu@example.com',
          address: '深圳市南山区科技园',
          registerDate: '2023-08-12T15:45:00',
          lastLogin: '2023-09-20T10:15:00',
          status: 'inactive',
          orderCount: 1,
          totalSpent: 12999,
          avatar: 'https://picsum.photos/seed/customer4/200/200'
        },
        {
          id: 5,
          name: '钱七',
          phone: '13500135005',
          email: 'qianqi@example.com',
          address: '杭州市西湖区文三路',
          registerDate: '2023-09-30T14:10:00',
          lastLogin: '2023-11-14T13:20:00',
          status: 'active',
          orderCount: 4,
          totalSpent: 10599,
          avatar: 'https://picsum.photos/seed/customer5/200/200'
        },
        {
          id: 6,
          name: '孙八',
          phone: '13400134006',
          email: 'sunba@example.com',
          address: '南京市鼓楼区中山路',
          registerDate: '2023-10-08T16:30:00',
          lastLogin: '2023-10-15T11:45:00',
          status: 'inactive',
          orderCount: 0,
          totalSpent: 0,
          avatar: 'https://picsum.photos/seed/customer6/200/200'
        },
        {
          id: 7,
          name: '周九',
          phone: '13300133007',
          email: 'zhoujiu@example.com',
          address: '成都市锦江区春熙路',
          registerDate: '2023-11-01T10:00:00',
          lastLogin: '2023-11-12T09:30:00',
          status: 'active',
          orderCount: 2,
          totalSpent: 5899,
          avatar: 'https://picsum.photos/seed/customer7/200/200'
        }
      ];
    }
  }
  
  // 获取所有客户
  getAllCustomers() {
    return [...this.customers];
  }
  
  // 获取活跃客户
  getActiveCustomers() {
    return this.customers.filter(customer => customer.status === 'active');
  }
  
  // 获取不活跃客户
  getInactiveCustomers() {
    return this.customers.filter(customer => customer.status === 'inactive');
  }
  
  // 根据ID获取客户
  getCustomerById(id) {
    return this.customers.find(customer => customer.id === id);
  }
  
  // 添加客户
  async addCustomer(customer) {
    try {
      const response = await ApiService.addCustomer(customer);
      if (response.success) {
        this.customers.push(response.data);
        this.saveToStorage();
        this.notifyListeners();
        return response.data;
      } else {
        throw new Error('Failed to add customer');
      }
    } catch (error) {
      console.error('Failed to add customer via API:', error);
      // API失败时的降级处理
      const newId = Math.max(0, ...this.customers.map(c => c.id)) + 1;
      const newCustomer = {
        id: newId,
        ...customer,
        registerDate: new Date().toISOString(),
        lastLogin: null,
        orderCount: 0,
        totalSpent: 0
      };
      this.customers.push(newCustomer);
      this.saveToStorage();
      this.notifyListeners();
      return newCustomer;
    }
  }
  
  // 更新客户
  async updateCustomer(id, updatedCustomer) {
    try {
      const response = await ApiService.updateCustomer(id, updatedCustomer);
      if (response.success) {
        const index = this.customers.findIndex(c => c.id === id);
        if (index !== -1) {
          this.customers[index] = response.data;
          this.saveToStorage();
          this.notifyListeners();
          return response.data;
        }
      } else {
        throw new Error('Failed to update customer');
      }
    } catch (error) {
      console.error('Failed to update customer via API:', error);
      // API失败时的降级处理
      const index = this.customers.findIndex(c => c.id === id);
      if (index !== -1) {
        // 保留不可编辑的字段
        const existingCustomer = this.customers[index];
        this.customers[index] = {
          ...this.customers[index],
          ...updatedCustomer,
          id: existingCustomer.id,
          registerDate: existingCustomer.registerDate,
          lastLogin: existingCustomer.lastLogin,
          orderCount: existingCustomer.orderCount,
          totalSpent: existingCustomer.totalSpent
        };
        this.saveToStorage();
        this.notifyListeners();
        return this.customers[index];
      }
    }
    return null;
  }
  
  // 删除客户
  async deleteCustomer(id) {
    try {
      const response = await ApiService.deleteCustomer(id);
      if (response.success) {
        const initialLength = this.customers.length;
        this.customers = this.customers.filter(customer => customer.id !== id);
        
        if (this.customers.length !== initialLength) {
          this.saveToStorage();
          this.notifyListeners();
          return true;
        }
      } else {
        throw new Error('Failed to delete customer');
      }
    } catch (error) {
      console.error('Failed to delete customer via API:', error);
      // API失败时的降级处理
      const initialLength = this.customers.length;
      this.customers = this.customers.filter(customer => customer.id !== id);
      
      if (this.customers.length !== initialLength) {
        this.saveToStorage();
        this.notifyListeners();
        return true;
      }
    }
    return false;
  }
  
  // 搜索客户
  searchCustomers(query) {
    if (!query) {
      return this.getAllCustomers();
    }
    
    const lowerQuery = query.toLowerCase();
    return this.customers.filter(customer => 
      customer.name.toLowerCase().includes(lowerQuery) ||
      customer.phone.includes(query) ||
      (customer.email && customer.email.toLowerCase().includes(lowerQuery))
    );
  }
  
  // 获取客户统计数据
  async getCustomerStats() {
    try {
      const response = await ApiService.getCustomerStats();
      if (response.success) {
        return response.data;
      } else {
        throw new Error('Failed to get customer stats');
      }
    } catch (error) {
      console.error('Failed to get customer stats via API:', error);
      // API失败时，本地计算统计数据
      const totalCustomers = this.customers.length;
      const activeCustomers = this.getActiveCustomers().length;
      const inactiveCustomers = this.getInactiveCustomers().length;
      const totalOrderCount = this.customers.reduce((sum, customer) => sum + (customer.orderCount || 0), 0);
      const totalSpent = this.customers.reduce((sum, customer) => sum + (customer.totalSpent || 0), 0);
      const avgOrderCount = totalCustomers > 0 ? (totalOrderCount / totalCustomers).toFixed(1) : 0;
      const avgSpent = totalCustomers > 0 ? (totalSpent / totalCustomers).toFixed(1) : 0;
      
      // 获取最近的客户
      const recentCustomers = [...this.customers]
        .sort((a, b) => new Date(b.registerDate) - new Date(a.registerDate))
        .slice(0, 5);
      
      return {
        totalCustomers,
        activeCustomers,
        inactiveCustomers,
        totalOrderCount,
        totalSpent,
        avgOrderCount,
        avgSpent,
        recentCustomers
      };
    }
  }
  
  // 获取最近注册的客户
  getRecentCustomers(limit = 5) {
    return [...this.customers]
      .sort((a, b) => new Date(b.registerDate) - new Date(a.registerDate))
      .slice(0, limit);
  }
  
  // 上传客户头像
  async uploadAvatar(file) {
    try {
      const response = await ApiService.uploadFile(file);
      if (response.success && response.data && response.data.url) {
        return response.data.url;
      } else {
        throw new Error('Failed to upload avatar');
      }
    } catch (error) {
      console.error('Failed to upload avatar via API:', error);
      // 生成模拟图片URL作为降级方案
      return `https://via.placeholder.com/200/4285f4/ffffff?text=${encodeURIComponent(file.name || 'Avatar')}`;
    }
  }
  
  // 根据姓名生成默认头像
  getDefaultAvatar(name) {
    // 根据姓名生成默认头像（使用随机头像服务）
    if (!name) return 'https://picsum.photos/seed/default/200/200';
    const seed = name.charCodeAt(0) + name.charCodeAt(name.length - 1);
    return `https://picsum.photos/seed/${seed}/200/200`;
  }
  
  // 批量删除客户
  async batchDeleteCustomers(ids) {
    try {
      const response = await ApiService.batchDeleteCustomers(ids);
      if (response.success) {
        this.customers = this.customers.filter(customer => !ids.includes(customer.id));
        this.saveToStorage();
        this.notifyListeners();
        return true;
      } else {
        throw new Error('Failed to batch delete customers');
      }
    } catch (error) {
      console.error('Failed to batch delete customers via API:', error);
      // API失败时的降级处理
      const initialLength = this.customers.length;
      this.customers = this.customers.filter(customer => !ids.includes(customer.id));
      
      if (this.customers.length !== initialLength) {
        this.saveToStorage();
        this.notifyListeners();
        return true;
      }
    }
    return false;
  }
  
  // 导出客户数据为CSV
  exportCustomersToCSV() {
    // 准备CSV内容
    const headers = ['客户ID', '姓名', '电话', '电子邮箱', '地址', '注册日期', '最后登录', '状态', '订单数', '总消费'];
    const csvContent = [
      headers.join(','),
      ...this.customers.map(customer => [
        customer.id,
        `"${customer.name}"`, // 包含逗号的字段需要用引号包围
        customer.phone,
        `"${customer.email || ''}"`,
        `"${customer.address || ''}"`,
        this.formatDate(customer.registerDate),
        customer.lastLogin ? this.formatDate(customer.lastLogin) : '从未登录',
        customer.status === 'active' ? '活跃' : '不活跃',
        customer.orderCount || 0,
        customer.totalSpent || 0
      ].join(','))
    ].join('\n');
    
    // 创建Blob和下载链接
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    link.setAttribute('href', url);
    link.setAttribute('download', `客户数据_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')}.csv`);
    link.style.visibility = 'hidden';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
  
  // 格式化日期
  formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
  }
  
  // 导入客户数据
  async importCustomersFromCSV(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      
      reader.onload = async (event) => {
        try {
          const csvContent = event.target.result;
          const lines = csvContent.split('\n');
          
          // 跳过表头
          if (lines.length < 2) {
            throw new Error('CSV文件格式不正确，没有数据行');
          }
          
          const newCustomers = [];
          const headers = lines[0].split(',');
          
          for (let i = 1; i < lines.length; i++) {
            if (!lines[i].trim()) continue;
            
            const values = this.parseCSVLine(lines[i]);
            if (values.length < 3) continue; // 至少需要姓名、电话等基本信息
            
            const customer = {
              name: this.cleanCSVValue(values[headers.indexOf('姓名')] || values[1]),
              phone: this.cleanCSVValue(values[headers.indexOf('电话')] || values[2]),
              email: this.cleanCSVValue(values[headers.indexOf('电子邮箱')] || values[3] || ''),
              address: this.cleanCSVValue(values[headers.indexOf('地址')] || values[4] || ''),
              status: 'active' // 默认设置为活跃状态
            };
            
            newCustomers.push(customer);
          }
          
          if (newCustomers.length === 0) {
            throw new Error('未找到有效的客户数据');
          }
          
          // 批量添加客户
          for (const customer of newCustomers) {
            await this.addCustomer(customer);
          }
          
          resolve(newCustomers.length);
        } catch (error) {
          reject(error);
        }
      };
      
      reader.onerror = () => {
        reject(new Error('读取文件失败'));
      };
      
      reader.readAsText(file, 'UTF-8');
    });
  }
  
  // 解析CSV行（处理引号内的逗号）
  parseCSVLine(line) {
    const values = [];
    let currentValue = '';
    let inQuotes = false;
    
    for (let i = 0; i < line.length; i++) {
      const char = line[i];
      
      if (char === '"') {
        inQuotes = !inQuotes;
      } else if (char === ',' && !inQuotes) {
        values.push(currentValue);
        currentValue = '';
      } else {
        currentValue += char;
      }
    }
    
    values.push(currentValue);
    return values;
  }
  
  // 清理CSV值（去除引号和前后空格）
  cleanCSVValue(value) {
    if (!value) return '';
    return value.replace(/^"|"$/g, '').trim();
  }
}

// 创建单例实例
export default new CustomerStore();